package com.remote.common.context.serialization;

import com.remote.common.model.Request;
import com.remote.common.model.Response;
import com.remote.common.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User:cool coding
 * Date:2018/1/7
 * Time:21:33
 * 编码
 */
public class ProtobufEncoder extends MessageToByteEncoder {
    private Class<?> genericClass;

    public ProtobufEncoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(ProtobufEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) {
        try {
            if (genericClass.isInstance(in)) {
                byte[] data = SerializationUtil.serialize(in);
                int length = data.length;
                out.writeInt(length);
                out.writeBytes(data);
            }
        } catch (Exception e) {
            if (genericClass == Request.class) {
                LOGGER.debug("编译服务端数据异常", e);
            } else if (genericClass == Response.class) {
                LOGGER.debug("编译客户端端数据异常", e);
            } else {
                LOGGER.debug("编译数据异常", e);
            }
        }
    }

    @Override
    public boolean isSharable() {
        return super.isSharable();
    }
}
